require(['./config'], () => {
    require(['template', 'header', 'footer'], (template) => {
        class Details {
            constructor () {
                this.getId().then(() => {
                    this.choseType()
                    this.choseNum()
                    this.addshopCar()
                    this.goodcarNum()
                })
                this.shopcarhref()
                this.loupe()      
            }
            // 从地址栏截取id的值，将id值添加到接口并请求数据进行渲染
            getId () {
                // console.log(location.search)
                // ?id=23332&from=pc
                return new Promise((resolve, reject) => {
                    const id = location.search.slice(4)
                    // 接口地址：https://show.bilibili.com/api/ticket/project/get?version=134&id=27244
                    $.get('/api/ticket/project/get', {
                        version: 134,
                        id: id
                    }, resp => {
                        if (resp.errno == 0) {
                            const {
                                id,
                                name,
                                project_label,
                                venue_info,
                                screen_list
                            } = resp.data
                            // 使用一个对象来存储数据,便于其他函数调用
                            this.details = {
                                id,
                                name,
                                project_label,
                                venue_info,
                                screen_list
                            }
                            $('#main').html(template('mainTemplate', { ...this.details }))
                            // 当渲染完成之后resolve
                            resolve()
                        }
                    })
                })
                
            }

            // 放大镜
            loupe () {
                $('#main').on("mouseenter mouseleave",'.content-left-img', (e) => {
                    if (e.type == "mouseenter") {
                        $('.content-left-img-mag').removeClass('dis')
                        $('.content-left-img span').removeClass('dis')

                        let imgbox = $('.content-left-img')
                        let warpbox = $('#main')
                        let span = $('.content-left-img span')
                        let spanwidth = span.innerWidth()
                        let spanheight = span.innerHeight()
                        let imgMax = $('.content-left-img-mag img')

                        $('#main').on('mousemove', '.content-left-img', e => {
                            let left = e.pageX - imgbox.offset().left - warpbox.offset().left - spanwidth / 2
                            let top = e.pageY  - imgbox.offset().top - warpbox.offset().top - spanheight / 4

                            
                            if(left < 0){
                                left = 0;
                            }else if(left > imgbox.innerWidth() - spanwidth){
                                left = imgbox.innerWidth() - spanwidth
                            }
                            if(top < 0){
                                top = 0;
                            }else if(top > imgbox.innerHeight() - spanheight){
                                top = imgbox.innerHeight() - spanheight
                            }
                            span.css({left:left})
                            span.css({top:top})
                            imgMax.css({left:-2*left})
                            imgMax.css({top:-2*top})
                        })

                    } else if (e.type == "mouseleave") {
                        $('.content-left-img-mag').addClass('dis')
                        $('.content-left-img span').addClass('dis')
                    }
                })
            }

            // 选择商品数量
            choseNum () {
                $('.sub').on('click', function () {
                    let num = $('.content-right-chose-num span').html()
                    num--
                    if (num <=1 ) {
                        num = 1
                    }
                    $('.content-right-chose-num span').html(num)
                })

                $('.plus').on('click', function () {
                    let num = $('.content-right-chose-num span').html()
                    num++
                    if (num > 4 ) {
                        num = 4
                        alert("购买票数超过单笔订单购买限制4张")
                    }
                    $('.content-right-chose-num span').html(num)
                })
            }

            // 选择商品类型
            choseType () {
                $('.content-right-chose').on('click', 'li', function () {
                    $(this).parent().children().removeClass('ac')
                    $(this).addClass('ac')
                })
            }

            // 加入购物车
            addshopCar () {
                $('#buybtn').on('click', () => {
                    // console.log(this.details)
                    var session, seid, price, prid
                    // 获取选择的场次以及场次id
                    $('.content-right-chose-session li').each(function () {
                        if ($(this).hasClass('ac')) {
                            session = $(this).html().trim()
                            seid = $(this).data('seid')
                        }
                    })
                    // 获取选择的价格以及价格id
                    $('.content-right-chose-price li').each(function () {
                        if ($(this).hasClass('ac')) {
                            price = $(this).html().trim()
                            prid = $(this).data('prid')
                        }
                    })
                    // 获取选择的数量
                    const num = parseInt($('.content-right-chose-num span').html())
                    
                    // 将数据存放到一个对象中
                    this.data = {
                        id: this.details.id,
                        name: this.details.name,
                        project_label: this.details.project_label,
                        session: session,
                        sessionid: seid,
                        price: price,
                        trueprice: Number(price.split("（")[0].split('￥')[1]),
                        priceid: prid
                    }
                    // console.log(this.data)
                    // 存到localstorage中
                    // localStorage.setItem('cart', JSON.stringify(this.data))
                    // 要存多条商品信息时 可将信息存为json数组

                    // 当点击加入购物车
                    // 先取出存到localstorage中判断里面是否有数据
                    // 如果没有, 就以数组格式存入当前数据
                    // 如果有, 就先将localstorage取出来, 修改, push到数组中, 再将数组存到localstorage中

                    let cart = localStorage.getItem('cart')
                    if (cart) {
                        // 购物车不为空
                        cart = JSON.parse(cart)
                        // 判断加入的数据是否和已有的数据相同
                        // 如果相同, 就改变商品数量
                        const isExist = cart.some(shop => {
                            return (shop.id === this.data.id)&&(shop.sessionid === this.data.sessionid)&&(shop.priceid === this.data.priceid)
                        })
                        if (isExist) {
                            // 商品存在
                            cart = cart.map(shop => {
                                if (((shop.id === this.data.id)&&(shop.sessionid === this.data.sessionid)&&(shop.priceid === this.data.priceid))) {
                                    shop.count += num
                                    if (shop.count > 4) {
                                        shop.count = 4
                                        alert("购买票数超过单笔订单购买限制4张")
                                    }
                                }
                                // 不管存不存在相同数据, 都要返回shop, cart才能完整
                                return shop
                            })
                        } else {
                            // 如果不存在相同的数据, 就push
                            // cart.push(this.data)
                            cart.push({ ...this.data , count: num , check: true})
                        }
                        // 不管存不存在相同数据, 都要存localstorage
                        localStorage.setItem('cart', JSON.stringify(cart))
                    } else {
                        // 购物车为空
                        localStorage.setItem('cart', JSON.stringify([ { ...this.data , count: num , check: true} ]))
                    }
                    this.goodcarNum()
                })
            }

            goodcarNum () {
                let count = 0
                let cart = localStorage.getItem('cart')
                if (cart) {
                    cart = JSON.parse(cart)
                    count = cart.reduce((num, shop) => {
                        num += shop.count
                        return num
                    }, 0)
                }
                $("#shopcar span b").html(count)
            }

            shopcarhref () {
                $('#shopcar').on('click', function () {
                    location.href = '/html/order.html'
                })
            }

        }
        new Details()
    })
})